<script setup lang="ts">
  import { computed, useAttrs } from 'vue'
  import { Icon } from '@iconify/vue'

  interface IconObject {
    type: 'iconify' | 'prime' | 'local'
    name: string
  }

  defineOptions({ name: 'SvgIcon', inheritAttrs: false })

  /**
   * Props
   *
   * - Support iconify and local svg icon
   * - If icon and localIcon are passed at the same time, localIcon will be rendered first
   */
  interface Props {
    /** Iconify icon name (支持字符串或对象格式) */
    icon?: string | IconObject
    /** PrimeIcons name (不需要 pi pi- 前缀) */
    prime?: string
    /** Local svg icon name */
    localIcon?: string
  }

  const props = defineProps<Props>()

  const attrs = useAttrs()

  const bindAttrs = computed<{ class: string; style: string }>(() => ({
    class: [
      (attrs.class as string) || '',
      // 如果是 PrimeIcons，添加必要的类名
      props.prime ? ['pi', `pi-${props.prime}`] : '',
    ]
      .filter(Boolean)
      .join(' '),
    style: (attrs.style as string) || '',
  }))

  const symbolId = computed(() => {
    // 从环境变量获取前缀，如果没有则使用默认值
    const prefix = import.meta.env.VITE_ICON_LOCAL_PREFIX || 'icon'
    const icon = props.localIcon || 'no-icon'
    return `#${prefix}-${icon}`
  })

  // 优先级：localIcon > prime > iconify
  const iconType = computed(() => {
    if (props.localIcon) return 'local'
    if (props.prime) return 'prime'
    if (props.icon && typeof props.icon === 'object' && props.icon.type === 'prime') return 'prime'
    if (props.icon) return 'iconify'
    return null
  })

  // 获取实际的 iconify 名称
  const iconifyName = computed(() => {
    console.log('iconifyName', props.icon)
    if (!props.icon) return ''
    return typeof props.icon === 'string' ? props.icon : props.icon.name
  })
</script>

<template>
  <template v-if="iconType === 'local'">
    <svg
      aria-hidden="true"
      v-bind="bindAttrs"
      :width="(attrs.width as string | number) || '1em'"
      :height="(attrs.height as string | number) || '1em'"
    >
      <use :xlink:href="symbolId" fill="currentColor" />
    </svg>
  </template>
  <template v-else-if="iconType === 'prime'">
    <i v-bind="bindAttrs" />
  </template>
  <template v-else-if="iconType === 'iconify'">
    <Icon :icon="iconifyName!" v-bind="bindAttrs" />
  </template>
</template>

<style scoped></style>
